package com.lu.project.interceptors;


import com.lu.project.common.ResultUtils;
import com.lu.project.constant.Constants;
import com.lu.project.constant.SecurityConstant;
import com.lu.project.constant.UserCacheConstant;
import com.lu.project.exception.BusinessException;
import com.lu.project.exception.ErrorCode;
import com.lu.project.properties.JwtTokenManagerProperties;
import com.lu.project.utils.EmptyUtil;
import com.lu.project.utils.JwtUtil;
import com.lu.project.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  多租户放到SubjectContent上下文中
 */
@Component
public class UserTokenIntercept implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //从头部中拿到当前userToken
        String userToken = request.getHeader(SecurityConstant.USER_TOKEN);
        if (!EmptyUtil.isNullOrEmpty(userToken)) {
            Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), userToken);
            //.get("currentUser");
            Object o = claims.get(Constants.JWT_USERID);
            String currentUser = String.valueOf(o);
            String jwtTokenKey = UserCacheConstant.JWT_TOKEN + currentUser;
            String jwtToken = redisTemplate.opsForValue().get(jwtTokenKey);

            if (!EmptyUtil.isNullOrEmpty(jwtToken)&&jwtToken.equals(userToken)) {

                //放入当前线程中：用户当前的web直接获得user使用
                UserThreadLocal.set(Long.parseLong(currentUser));

            }else {
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户未登录,请登录");
            }
        }else {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"当前用户未登录，请登录");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除当前线程中的参数
        UserThreadLocal.removeSubject();
    }
}
